<?php

namespace Models\Validators;

class StringLength extends ValidatorAbstract {
    
    protected $_errorMsgPattern = [
        'min'  => '%s must contain at least %d characters',
        'max'  => 'Maximum length of %s is %d characters',
    ];
    
    protected $_restrictions = [];
    
    public function __construct($options) {
        
        if (!isset($options['min']) && !isset($options['max'])) {
            throw new \Exception('Min or Max restriction must be present');
        }
        
        if (isset($options['max'])) {
            $this->_restrictions['max'] = $options['max'];
        }
        
        if (isset($options['min'])) {
            $this->_restrictions['min'] = $options['min'];
        }
    }
    
    public function isValid($elementName, $value) {
        
        if (    isset($this->_restrictions['min']) 
             && strlen($value) < $this->_restrictions['min']
        ) {
            
            $this->_buildErrorMessage($elementName, 'min');
            return false;
        }
        
        if (    isset($this->_restrictions['max']) 
             && strlen($value) > $this->_restrictions['max']
        ) {
            
            $this->_buildErrorMessage($elementName, 'max');
            return false;
        }
        
        return true;
    }
    
    protected function _buildErrorMessage($elementName, $restrictionType) {

        $this->_errorMsg = sprintf(
            $this->_errorMsgPattern[$restrictionType], 
            $elementName, 
            $this->_restrictions[$restrictionType]
        );
    }

}